import {
  login,
  logout,
  getInfo
} from '@/api/auth'
import {
  getUserMenus
} from '@/api/admin-user'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import {
  resetRouter,
  constantRoutes
} from '@/router'
import RouteMap from '@/router/router-map.js'

export function generateRoutes(routes) {
  const res = []

  routes.forEach(item => {
    const tmp = {
      path: item.path,
      name: item.name,
      redirect: item.redirect,
      component: RouteMap[item.name],
      meta: {
        title: item.title,
        icon: item.icon,
        noCache: item.no_cache,
        breadcrumb: item.breadcrumb,
        affix: item.affix
      }
    }

    if (item.children) {
      tmp.children = generateRoutes(item.children)
    }
    res.push(tmp)
  })

  return res
}

const getDefaultState = () => {
  return {
    token: getToken(),
    info: null,
    accessedRoutes: [],
    addRoutes: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_INFO: (state, userInfo) => {
    state.info = userInfo
  },
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.accessedRoutes = constantRoutes.concat(routes)
  }
}

const actions = {
  // 用户登录
  login({
    commit
  }, userInfo) {
    const {
      username,
      password
    } = userInfo
    return new Promise((resolve, reject) => {
      login({
        username: username.trim(),
        password: password
      }).then(response => {
        const {
          data
        } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token, data.expires)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const {
          data
        } = response

        if (!data) {
          return reject('获取用户信息失败，请重新登录')
        }
        commit('SET_USER_INFO', data)

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 用户退出登录
  logout({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // 删除cookie里存储的token
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 删除token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      removeToken() // 删除cookie里存储的token
      commit('RESET_STATE')
      resolve()
    })
  },

  // 获取用户菜单路由
  getMenus({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getUserMenus(state.info.id).then(response => {
        const {
          data
        } = response

        const accessedRoutes = generateRoutes(data.list)
        accessedRoutes.push({
          path: '*',
          redirect: '/404',
          hidden: true
        })
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
